package com.hejjon;

/**
 *  5. 最长回文子串
 * Created by caoshi at 21:27 2021-10-22
 */
public class Palindrome {

    public static void main(String[] args) {
        Palindrome p = new Palindrome();
//        String s = "abcba";
        String s = "abb";

        String res = p.longestPalindrome(s);

        System.out.println(res);
    }


    public String longestPalindrome(String s) {
        String res = "";

        for (int i = 0; i < s.length(); i++) {
            // 当回文子串长度是奇数时, 从同一个中心点向外扩散
            String s1 = palindrome(s, i, i);
            //
            String s2 = palindrome(s, i, i + 1);

            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;

        }
        return res;
    }


    public String palindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length()) {
            if (s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            } else {
                break;
            }
        }
        return s.substring(left + 1, right);
    }


}
